package com.sunlong.jiangwei.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunlong.jiangwei.dao.JwUserAddresslistMapper;
import com.sunlong.jiangwei.dao.RoleMapper;
import com.sunlong.jiangwei.dao.UserMapper;
import com.sunlong.jiangwei.entity.JwRole;
import com.sunlong.jiangwei.entity.JwUser;
import com.sunlong.jiangwei.entity.JwUserAddresslist;
import com.sunlong.jiangwei.entity.JwUserRole;
import com.sunlong.jiangwei.service.IUserService;
import com.sunlong.jiangwei.util.ErrorMapUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private JwUserAddresslistMapper addresslistMapper;

    @Override
    public List<JwUser> findAllAdminUser(Map<String, Object> map) {
        if (null == map.get("type")) {
            return userMapper.findAllAdminUser();
        }else {
            Integer type = (Integer) map.get("type");
            Long storeId = ((Integer) map.get("storeId")).longValue();
            JwUser jwUser = new JwUser();
            jwUser.setType(type);
            jwUser.setStoreId(storeId);
            List<JwUser> select = userMapper.select(jwUser);
            return select;
        }
    }

    /**
     * 验证登录
     *
     * @param map
     * @return
     */
    @Override
    public Map<String, String> login(Map<String, Object> map) {
        String user = (String) map.get("user");
        String password = (String) map.get("password");
        Integer type = (Integer) map.get("type");

        JwUser user1 = userMapper.selectByUsername(user, type);
        HashMap<String, String> map1 = new HashMap<>();
        if (null == user1) {
            ErrorMapUtils.putErrorMap(map1, "用户不存在");
            return map1;
        }
        String md5Pass = getMd5Pass(password);
        if (md5Pass.equals(user1.getPassword())) {
            map1.put("login", "yes");
            map1.put("user", JSONObject.toJSONString(user1));
        } else {
            map1.put("login", "no");
        }
        return map1;
    }

    /**
     * 新增用户
     *
     * @param map
     * @return
     */
    @Override
    public Map<String, String> add(Map<String, Object> map) {
        String user = (String) map.get("user");
        String password = (String) map.get("password");
        String phone = (String) map.get("phone");
        Integer type = (Integer) map.get("type");
        JwUser user1 = userMapper.selectByUsername(user, type);
        HashMap<String, String> map1 = new HashMap<>();
        if (null != user1) {
            ErrorMapUtils.putErrorMap(map1, "用户名已存在");
            return map1;
        }
        String md5Pass = getMd5Pass(password);
        JwUser jwUser = new JwUser();
        jwUser.setUsername(user);
        jwUser.setPassword(md5Pass);
        jwUser.setPhone(phone);
        jwUser.setType(type);
        jwUser.setCreated(new Date());
        userMapper.insert(jwUser);
        return map1;
    }

    @NotNull
    private String getMd5Pass(String password) {
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    /**
     * 根据id删除用户
     *
     * @param map
     * @return
     */
    @Transactional
    @Override
    public Map<String, String> delete(Map<String, Object> map) {
        Long userId = ((Integer) map.get("id")).longValue();
        userMapper.deleteUserById(userId);
        userMapper.deleteUserRoleById(userId);
        return null;
    }

    /**
     * 查询用户以及用户下的所有角色
     *
     * @return
     */
    @Override
    public List<JwUser> userRoleList() {
        List<JwUser> jwUsers = userMapper.findAllAdminUser();
        for (JwUser jwUser : jwUsers) {
            List<JwUserRole> jwUserRoles = userMapper.selectUserRoleById(jwUser.getUserId());
            if (jwUserRoles.size() <= 0){
                jwUser.setRoleNames("-");
            }else {
                String names = "";
                JwRole role = roleMapper.selectRoleById(jwUserRoles.get(0).getRoleId());
                names += role.getRoleName();
                jwUser.setRoleNames(names);
                jwUser.setRoleId(role.getRoleId());
            }
        }
        return jwUsers;
    }

    /**
     * 保存或者修改用户角色对应关系
     * @param map
     * @return
     */
    @Override
    public Map<String, String> userRoleModify(Map<String, Object> map) {
        Integer userId = (Integer) map.get("userId");
        Integer roleId = (Integer) map.get("roleId");
        List<JwUserRole> jwUserRoles = userMapper.selectUserRoleById(userId.longValue());
        if (jwUserRoles.size() <= 0){
            userMapper.insertUserRole(userId.longValue(),roleId.longValue());
        }else {
            userMapper.updateUserRole(userId.longValue(),roleId.longValue());
        }
        return null;
    }

    @Override
    public Map<String, String> userRoleDelete(Map<String, Object> map) {
        Integer userId = (Integer) map.get("userId");
        userMapper.deleteUserRoleById(userId.longValue());
        return null;
    }

    /**
     * 修改密码
     * @param map
     * @return
     */
    @Override
    public Map<String, String> changePassword(Map<String, Object> map) {
        Integer type = (Integer) map.get("type");
        String username = (String) map.get("username");
        String oldPassword = (String) map.get("oldPassword");
        String newPassword = (String) map.get("newPassword");
        JwUser jwUser = userMapper.selectByUsername(username, type);
        HashMap<String, String> errorMap = new HashMap<>();
        String password = jwUser.getPassword();
        if (!password.equals(getMd5Pass(oldPassword))){
            ErrorMapUtils.putErrorMap(errorMap,"密码不匹配");
            return errorMap;
        }
        userMapper.modifyPassword(username,getMd5Pass(newPassword),type);
        return null;
    }

    /**
     * 使用用户注册
     * @param map
     * @return
     */
    @Transactional
    @Override
    public Map<String, String> register(Map<String, Object> map) {
        Integer type = (Integer) map.get("type");
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        String phoneNum = (String) map.get("phoneNum");
        String consigneeName = (String) map.get("consigneeName");
        String address = (String) map.get("address");
        JwUser jwUser1 = userMapper.selectByUsername(username, type);
        HashMap<String, String> errorMap = new HashMap<>();
        if (null != jwUser1){
            ErrorMapUtils.putErrorMap(errorMap,"用户名已存在！");
            return errorMap;
        }
        JwUser jwUser = new JwUser();
        jwUser.setUsername(username);
        jwUser.setCreated(new Date());
        jwUser.setType(type);
        jwUser.setPhone(phoneNum);
        jwUser.setPassword(getMd5Pass(password));
        userMapper.insert(jwUser);
        JwUserAddresslist addresslist = new JwUserAddresslist();
        addresslist.setUserId(jwUser.getUserId());
        addresslist.setConsigneeName(consigneeName);
        addresslist.setConsigneeAddress(address);
        addresslist.setConsigneePhone(phoneNum);
        addresslistMapper.insert(addresslist);
        return errorMap;
    }
}
